<template>
  <div class="address box mb-15" style="border-radius: 4px">
    <div>
      <span>{{ $t('钱包地址') }}：</span>
      <span>{{ fromAddressHideRef }}</span>
    </div>

    <div class="flex flex-rb">
      <div>
        <span>{{ $t('购物券') }}：</span>
        <span>{{ coupon }}</span>
      </div>

      <div class="cl-success click" @click="rechargeVisible = true">
        {{ $t('充值购物券') }}
      </div>
    </div>

    <!-- 充值购物券 -->
    <van-popup v-model:show="rechargeVisible">
      <div class="popup">
        <div class="fz-20 mb-15">{{ $t('充值') }}</div>

        <!-- 介绍 -->
        <div class="mb-15">{{ $t('充值介绍1') }}</div>
        <div class="mb-15">{{ $t('充值介绍2') }}</div>

        <!-- 充值金额 -->
        <div class="mb-15">
          <div class="mb-10">{{ $t('充值金额') }}</div>
          <van-field
            type="digit"
            :placeholder="$t('请输入充值金额')"
            @input="getNeedPrice"
            v-model="amount"
          ></van-field>
        </div>

        <div class="flex flex-rc">
          <van-button
            style="width: 100px"
            type="primary"
            round
            @click="recharge"
          >
            {{ $t('充值') }}
          </van-button>
        </div>

        <div class="fz-12 mt-10">
          {{ $t('充值提示', { usdt: needUsdt, pandax: needPandax }) }}
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, inject } from 'vue'
import mitt from 'js/mitt'
import {
  toNumber,
  toBigNumber,
  showToast,
  showSuccess,
  showError,
  showLoading,
} from 'js/utils'

// 余额
const balance = inject('balance')
const pandax = inject('pandax')
const coupon = inject('coupon')

// 地址
const fromAddressHideRef = ref(window.fromAddressHide)

// 本次充值扣除
const needUsdt = ref(0)
const needPandax = ref(0)

// 充值表单
const amount = ref('')
const rechargeVisible = ref(false)

// 充值购物券
async function recharge() {
  if (Number(balance.value) < Number(needUsdt.value)) {
    return showToast($t('Usdt余额不足'))
  }

  if (Number(pandax.value) < Number(needPandax.value)) {
    return showToast($t('Pandax余额不足'))
  }

  const loading = showLoading()

  try {
    // 判断用户Usdt授权给Coupon的额度是否足够，不够就先授权额度
    const authorizedBalanceByUsdt = await getAuthorizedBalanceByUsdt()

    if (authorizedBalanceByUsdt <= 0) {
      // 需要授权额度
      await authorizeBalanceByUsdt()
    } else if (authorizedBalanceByUsdt < Number(needUsdt.value)) {
      // 可用额度小于用户投资的金额
      await authorizeBalanceByUsdt()
    }

    // 判断用户Pandax授权给Coupon的额度是否足够，不够就先授权额度
    const authorizedBalanceByPandax = await getAuthorizedBalanceByPandax()

    if (authorizedBalanceByPandax <= 0) {
      // 需要授权额度
      await authorizeBalanceByPandax()
    } else if (authorizedBalanceByPandax < Number(needPandax.value)) {
      // 可用额度小于用户投资的金额
      await authorizeBalanceByPandax()
    }

    // 下单
    await investAmount()
    loading?.close()
  } catch (err) {
    console.error(err)
    loading?.close()
  }
}

// 下单
function investAmount() {
  return new Promise(async (resolve, reject) => {
    try {
      console.log(`充值金额：${amount.value}`)
      const res = await couponContract.context.methods
        .exchange(toBigNumber(amount.value))
        .send({
          from: fromAddress,
        })
      amount.value = ''
      mitt.emit('refresh')
      showSuccess($t('充值成功'))
      console.log('充值成功')
      console.log(res)
      resolve(res)
    } catch (err) {
      amount.value = ''
      showError($t('充值失败'))
      console.error('充值失败')
      console.error(err)
      reject(err)
    }
  })
}

// Usdt授权Coupon额度
function authorizeBalanceByUsdt() {
  return new Promise(async (resolve, reject) => {
    try {
      const quota = toBigNumber(100000) // 授权 100000 Usdt额度
      const res = await usdtContract.context.methods
        .approve(couponContract.context._address, quota)
        .send({
          from: fromAddress,
        })
      showSuccess($t('授权余额成功'))
      console.log(`授权Usdt余额成功：${toNumber(quota)}`)
      console.log(res)
      resolve(quota)
    } catch (err) {
      showError($t('授权余额失败'))
      console.error('授权Usdt余额失败')
      console.error(err)
      reject(err)
    }
  })
}

// 获取Usdt授权给Coupon的额度
function getAuthorizedBalanceByUsdt() {
  return new Promise(async (resolve, reject) => {
    try {
      const authorizedBalance = await usdtContract.context.methods
        .allowance(fromAddress, couponContract.context._address)
        .call()
      const authorizedBalanceInBigNumber = Number(toNumber(authorizedBalance))
      console.log(`获取Usdt授权余额成功：${authorizedBalanceInBigNumber}`)
      resolve(authorizedBalanceInBigNumber)
    } catch (err) {
      showError($t('获取授权余额失败'))
      console.error('获取Usdt授权余额失败')
      console.error(err)
      reject(err)
    }
  })
}

// Pandax授权Coupon额度
function authorizeBalanceByPandax() {
  return new Promise(async (resolve, reject) => {
    try {
      const quota = toBigNumber(100000) // 授权 100000 Pandax额度
      const res = await pandaxContract.context.methods
        .approve(couponContract.context._address, quota)
        .send({
          from: fromAddress,
        })
      showSuccess($t('授权余额成功'))
      console.log(`授权Pandax余额成功：${toNumber(quota)}`)
      console.log(res)
      resolve(quota)
    } catch (err) {
      showError($t('授权余额失败'))
      console.error('授权Pandax余额失败')
      console.error(err)
      reject(err)
    }
  })
}

// 获取Pandax授权给Coupon的额度
function getAuthorizedBalanceByPandax() {
  return new Promise(async (resolve, reject) => {
    try {
      const authorizedBalance = await pandaxContract.context.methods
        .allowance(fromAddress, couponContract.context._address)
        .call()
      const authorizedBalanceInBigNumber = Number(toNumber(authorizedBalance))
      console.log(`获取Pandax授权余额成功：${authorizedBalanceInBigNumber}`)
      resolve(authorizedBalanceInBigNumber)
    } catch (err) {
      showError($t('获取授权余额失败'))
      console.error('获取Pandax授权余额失败')
      console.error(err)
      reject(err)
    }
  })
}

// 获取本次充值所需的Usdt和Pandax
async function getNeedPrice() {
  try {
    if (amount.value) {
      const price = await couponContract.context.methods
        .getPrice(toBigNumber(amount.value))
        .call()
      needUsdt.value = toNumber(price._usdtAmount)
      needPandax.value = toNumber(price._paxAmount)
      console.log('获取所需的Usdt和Pandax成功')
    } else {
      needUsdt.value = 0
      needPandax.value = 0
    }
  } catch (err) {
    console.error('获取所需的Usdt和Pandax失败')
    console.error(err)
  }
}
</script>

<style lang="scss" scoped></style>
